package p.sunmes.les.actor;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.esotericsoftware.spine.AnimationState;
import com.esotericsoftware.spine.AnimationStateData;
import com.esotericsoftware.spine.Skeleton;
import com.esotericsoftware.spine.SkeletonMeshRenderer;

import p.sunmes.les.managers.RM;

public class SpineActor extends Actor {

	Skeleton skeleton;
	AnimationState animation;
	SkeletonMeshRenderer render;

	private Vector2 vectorPosition = new Vector2();

	public Skeleton getSkeleton() {
		return skeleton;
	}

	public AnimationState getAnimation() {
		return animation;
	}

	public SpineActor(Skeleton skeleton) {
		this.skeleton = skeleton;
		AnimationStateData data = new AnimationStateData(skeleton.getData());
		animation = new AnimationState(data);
		render = new SkeletonMeshRenderer();
		render.setPremultipliedAlpha(false);
	}

	@Override
	public void setColor(Color color) {
		skeleton.setColor(color);
	}

	@Override
	public void setColor(float r, float g, float b, float a) {
		skeleton.setColor(new Color(r, g, b, a));
	}

	@Override
	public Color getColor() {
		return skeleton.getColor();
	}

	@Override
	public void act(float delta) {
		animation.update(delta);
		animation.apply(skeleton);

		vectorPosition.set(getX(), getY());
		if (getParent() != null) {
			getParent().localToStageCoordinates(vectorPosition);
		}
		skeleton.setPosition(vectorPosition.x, vectorPosition.y);
		skeleton.getRootBone().setScaleX(getScaleX());
		skeleton.getRootBone().setScaleY(getScaleY());

		skeleton.updateWorldTransform();
		super.act(delta);
	}

	float tmpAlpha;

	@Override
	public void draw(Batch batch, float parentAlpha) {
		tmpAlpha = skeleton.getColor().a;
		skeleton.getColor().a *= parentAlpha;
		batch.end();
		RM.instance().getPolygonBatch()
				.setProjectionMatrix(batch.getProjectionMatrix());
		//M.rm.getPolygonBatch().setTransformMatrix(batch.getTransformMatrix());
		RM.instance().getPolygonBatch().begin();
		render.draw(RM.instance().getPolygonBatch(), skeleton);
		RM.instance().getPolygonBatch().end();
		batch.begin();
		skeleton.getColor().a = tmpAlpha;
	}

	public void draw() {
		RM.instance().getPolygonBatch().begin();
		render.draw(RM.instance().getPolygonBatch(), skeleton);
		RM.instance().getPolygonBatch().end();
	}

	public Vector2 getVectorPosition() {
		return vectorPosition;
	}

}
